import { reactive, onMounted, defineComponent, toRefs, getCurrentInstance, ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadInstance, UploadProps, UploadUserFile } from 'element-plus'
import requestApi from '@/api/purchase/request-api'
import warehouseApi from '@/api/inwarehouse/warehouse-api'
import projectApi from '@/api/inwarehouse/project-api'
import requirementApi from '@/api/purchase/requirement-api'
import goodsApi from '@/api/inwarehouse/goods-api'
import ZlrtTable from '@/components/zlrt-table/table.vue'
import ZlrtSearch from '@/components/zlrt-search/search.vue'
import TableContext from '@/components/zlrt-table/table-context'
import { exportExcel } from '@/utils/exprotExcel'
import inventoryApi from '@/api/inwarehouse/inventory-api'

export default defineComponent({
  components: {
    ZlrtTable,
    ZlrtSearch
  },
  setup() {
    const statusOptions = [
      { value: '0', label: '新增' },
      { value: '99', label: '已完成' },
      { value: '100', label: '已同步' }
    ]

    const ctx = reactive(new TableContext(getCurrentInstance(), {
      title: '请购单',
      api: requestApi,
      columns: [
        // { prop: 'serialId', label: '单号', valueType: 'input' },
        { prop: 'projectName', label: '项目', valueType: 'input' },
        { prop: 'date', label: '日期', slot: true, width: '270' },
        { prop: 'status', label: '状态', slot: true, valueType: 'select', options: statusOptions, width: '120' },
        { prop: 'operation', label: '操作', slot: true, width: '150' }
      ],
      other: {
        searchSku: async (row) => {
          const res = await goodsApi.list({ otherFilter: { skuName: row.searchSkuName, specification: row.searchSpecification } });
          if (res.success) {
            row.goodsList = res.data.records;
          }
        },
        async pass(row) {
          const obj = { ...row }
          obj['blueprintName'] = JSON.stringify(obj['blueprintName']);
          obj['status'] = '99'
          // console.log()
          const res = await requestApi.save(obj)
          if (res.code === 200) {
            ElMessage.success('审核通过');
            ctx.editVisible = false
            ctx.loadData()
          }
        },
        formatDt(val) {
          if (!val) {
            return '-'
          }
          return val.substring(0, 10)
        },
        getStatus(val) {
          if (!val) {
            return '-'
          }
          return statusOptions.find(item => {
            return item.value === val
          }).label
        },
        handelProjectChange(val: string) {
          const obj = data.projectOptions.find(item => {
            return item.name === val
          })
          if (!obj) {
            return
          }
          ctx.editData.projectId = obj['id']
          ctx.editData.projectOriginalNo = obj['originalNo']
          getRequirement(obj['id'])
        },
        async handelBpnChange(val) {
          let arr = [];
          val?.map(item => {
            const obj = data.requirementOrder.find(dro => item === dro.blueprintName);
            const orderGoodsList = obj.orderGoodsList;
            orderGoodsList?.map(ogl => {
              const temp = JSON.parse(JSON.stringify(ogl));
              const index = arr.findIndex(ar => ar.barCode === temp.barCode);
              if(index === -1) {
                temp['number'] = ogl.number * getBoxNum(item);
                arr.push(temp);
              } else {
                arr[index].number = (arr[index].number * 1000 + ogl.number * getBoxNum(item) * 1000) / 1000;
              }
            })
          })
          ctx.editData.orderGoodsList = arr
        },
        // export: () => {
        //   exportExcel({
        //     column: [
        //       { label: '存货编码', name: 'barCode' },
        //       { label: '品名', name: 'skuName' },
        //       { label: '规格型号', name: 'specification' },
        //       { label: '请购数量', name: 'number' },
        //     ], data: ctx.editData.orderGoodsList, filename: ctx.editData.projectName + '-请购物料', autoWidth: true, format: 'xlsx'
        //   });
        // },
        async save() {
          if(!ctx.editData.orderGoodsList || ctx.editData.orderGoodsList.length === 0) {
            ElMessage.warning('暂无请购物料');
            return
          }
          const orderGoodsList = JSON.parse(JSON.stringify(ctx.editData.orderGoodsList));
          const index = orderGoodsList.findIndex(item => item.number === 0);
          if(index > -1) {
            const skuName = orderGoodsList[index].skuName;
            ElMessage.warning(`${skuName}请购数量为0`);
            return
          }
          data.finishLoading = true;
          orderGoodsList.map(ceol => {
            ceol['goodsId'] = ceol['id'];
            delete ceol['id'];
          })
          const params = {
            ...ctx.editData,
            date: new Date(),
            blueprintName: JSON.stringify(ctx.editData.blueprintName),
            orderGoodsList,
            status: '0'
          }
          const res = await requestApi.save(params);
          data.finishLoading = false;
          if(res.success) {
            ElMessage.success(`${ctx.editAction}成功`);
            ctx.loadData();
            ctx.editVisible = false;
          }
          //
        },
        async showDetail(row) {
          detailCtx.editLoading = true;
          const res = await requestApi.detail(row.id)
          detailCtx.editData = res.data;
          detailCtx.editLoading = false;
          detailCtx.editVisible = true;
        },
        addGoods() {
          if (!ctx.editData['orderGoodsList']) {
            ctx.editData['orderGoodsList'] = []
          }
          ctx.editData['orderGoodsList'].push({})
        },
        delGoods() {
          data.delGoodsList.map(dgl => {
            const index = ctx.editData['orderGoodsList'].findIndex(item => {
              return item.id === dgl.id
            })
            ctx.editData['orderGoodsList'].splice(index, 1)
          })
        },
        handleGoodsSelectionChange(val: any) {
          console.log('requestVal',val)
          if (!ctx.editData['orderGoodsList']) {
            return
          }
          data.delGoodsList = val
        },
        getList(list) {
          if(!list || list.length === 0) {
            return {
              flag: false,
              data: []
            }
          }
          const arr = list.filter(item => {
            return item.number > 0
          })
          return {
            flag: true,
            data: arr
          }
        },
        async showEdit(row) {
          // data.blueprintName = '';
          const { id, projectId } = row;
          ctx.editLoading = true;
          await getRequirement(projectId);
          const res = await requestApi.detail(id);
          ctx.editLoading = false;
          if(res.success) {

            ctx.editData = res.data;
            if(ctx.editData['blueprintName']) {
              ctx.editData['blueprintName'] = JSON.parse(ctx.editData['blueprintName']);
            }
            ctx.editVisible = true;
          }
        }
      }
    }))

    const detailCtx = reactive({
      editVisible: false,
      editData: {
        orderGoodsList: []
      },
      editLoading: false
    })

    const getRequirement = async (projectId) => {
      if(!projectId) {
        data.requirementOrder = [];
        return
      }
      const params = {filter: { projectId }}
      const res = await requirementApi.listCount(params)
      data.requirementOrder = res.data;
      if(!ctx.editData.id) {
        const arr = [];
        data.requirementOrder?.map(dro => {
          arr.push(dro.blueprintName)
        })
        ctx.editData.blueprintName = arr;
        ctx.other.handelBpnChange(ctx.editData.blueprintName);
      } else {
        // data.blueprintName = JSON.parse(ctx.editData.blueprintName);
        // console.log(ctx.editData)
        // Object.assign(ctx.editData, {
        //   blueprintName: JSON.parse(ctx.editData.blueprintName)
        // })
      }
    }

    const addRemark = (row1, row2) => {
      let temprRemark = row2.remark;
      if(!row2.remark || row2.remark === '' || row2.remark.indexOf('库存总数') === -1) {
        temprRemark = row2.skuName + '库存总数:' + getInventoryNum(row2.inventoryList) + '；';
      }
      if(temprRemark.indexOf(row1.projectName) > -1) {
        return
      }
      const remark = temprRemark + `${row1.projectName}库存数量:${row1.number}；`;
      Object.assign(row2, {
        remark
      })
    }

    // const getRequirementDetail = async (id) => {
    //   const res = await requirementApi.detail(id);
    //   return res.data
    // }

    const getGoodsList = async (val: string) => {
      data.loading = true;
      const params = { otherFilter: { skuName: val } }
      const res = await goodsApi.list(params)
      data.loading = false;
      data.goodsOptions = res.data.records;
    }

    const getGoodsListCode = async (val: string) => {
      data.goodsOptionsCode = [];
      data.loading = true;
      const params = { otherFilter: { barCode: val } }
      const res = await goodsApi.list(params)
      // data.getCodeObj = res
      data.loading = false;
      data.goodsOptionsCode = res.data.records;
    }

    const handleSkuChangeCode = (val, scope) => {
      const obj = data.goodsOptionsCode.find(item => {
        return item.barCode === val
      })
      getInventoryList(obj, scope)
    }

    // const getInventoryListCode = async (obj: any, scope: any) => {
    //   console.log('111log')
    //   const params = {filter: {barCode: obj.barCode}}
    //   const res = await inventoryApi.list(params)
    //   const inventoryList = res.data.records;
    //   obj['inventoryList'] = inventoryList;
    //   obj['number'] = 0;
    //   if(scope.row.barCode) {
    //     obj['reqSkuName'] = obj.reqSkuName;
    //     obj['reqSpecification'] = obj.reqSpecification;
    //     obj['reqRemark'] = obj.reqRemark;
    //     obj['reqNumber'] = obj.reqNumber;
    //     obj['number'] = obj.number;
    //     // obj['skuName'] = scope.row.skuName;
    //     const index = ctx.editData.orderGoodsList.findIndex(item => item.skuName === obj.skuName);
    //     ctx.editData.orderGoodsList.splice(index, 1, obj);
    //     const params = {
    //       projectId:ctx.editData.projectId,
    //       goodsId: obj.id,
    //       oldBarCode: scope.row.barCode,
    //       newBarCode: obj.barCode,
    //       skuName: obj.skuName,
    //       isCheck: true,
    //       numberCheck: obj['number']
    //     }
    //     changedGood(params)
    //   } else {
    //     Object.assign(scope.row, obj);
    //   }
    //   data.goodsOptions = [{...obj}];
    // }

    const handleSkuChange = (val, scope) => {
      const obj = data.goodsOptions.find(item => {
        return item.skuName === val
      })
      getInventoryList(obj, scope)
    }

    const getInventoryList = async (obj: any, scope: any) => {
      const params = {filter: {barCode: obj.barCode}}
      const res = await inventoryApi.list(params)
      const inventoryList = res.data.records;
      obj['inventoryList'] = inventoryList;
      obj['number'] = 0;
      if(scope.row.barCode) {
        obj['reqSkuName'] = scope.row.reqSkuName;
        obj['reqSpecification'] = scope.row.reqSpecification;
        obj['reqRemark'] = scope.row.reqRemark;
        obj['reqNumber'] = scope.row.reqNumber;
        obj['number'] = scope.row.number;
        const index = ctx.editData.orderGoodsList.findIndex(item => item.barCode === scope.row.barCode);
        ctx.editData.orderGoodsList.splice(index, 1, obj);
        const params = {
          projectId:ctx.editData.projectId,
          goodsId: obj.id,
          oldBarCode: scope.row.barCode,
          newBarCode: obj.barCode,
          skuName: obj.skuName,
          isCheck: true,
          numberCheck: obj['number']
        }
        changedGood(params)
      } else {
        Object.assign(scope.row, obj);
      }
      data.goodsOptions = [{...obj}];
    }

    const changedGood = async (params) => {
      const res = await projectApi.changeBarCode(params)
      if(res.success) {
        ElMessage.success('修改成功');
      }
    }

    const getBoxNum = (str) => {
      if(!str) {
        return
      }
      let arr = []
      if(str.indexOf('\\') > -1) {
        arr = str.split('\\');
      }
      return arr.length
    }

    const getProjectList = async () => {
      const params = { filter: { disabled: 2 } }
      const res = await projectApi.list(params)
      data.projectOptions = res.data.records
    }

    const uploadRef = ref<UploadInstance>()

    // 需求清单上传
    const uploadFile = async (options) => {
      data.requirementGoodList = []
      ctx.editData = {}
      data.importLoading = true
      data.requirementList = []
      const res = await requirementApi.upload({ file: options.file })
      data.importLoading = false
      data.fileList = []
      if (res.data && res.data.length > 0) {
        res.data?.map(o => {
          o.searchSkuName = o.skuName;
          o.searchSpecification = o.specification;
          // o.goodsList?.map(x => {
          //   x.needNumber = o.number;

          // });
        })
        data.requirementList = res.data
        data.requirementDialog = true
      }
    }

    const confirm = () => {
      const ogl = []
      data.requirementList.map(item => {
        item.goodsList.map(gl => {
          if(gl['needNumber']) {
            const obj = { ...gl }
            obj['goodsId'] = obj['id']
            obj['number'] = obj['needNumber']
            delete obj['id']
            delete obj['needNumber']
            ogl.push(obj)
          }
        })
      })
      if(!ogl || ogl.length === 0) {
        ElMessage.warning('请检查请购数量');
        return;
      }

      ElMessageBox.confirm(`确认当前已选数据生成请购单？`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true
      })
        .then(async () => {
          const params = {
            ...ctx.editData,
            status: '0',
            date: new Date(),
            orderGoodsList: ogl
          }
          const res = await requestApi.save(params)
          if (res.code === 200) {
            ElMessage.success('新增成功')
            ctx.loadData()
            data.requirementDialog = false
          }
        })
        .catch()
    }

    const getInventoryNum = (arr?: any) => {
      if(!arr || arr.length === 0) {
        return 0
      }
      let num = 0;
      arr.map(ar => {
        num = (num * 1000 + ar.number * 1000) / 1000;
      })
      return num
    }

    const tableRowStyle = () => {
      return 'background: #FAFAFA'
    }

    const abandon = () => {
      ElMessageBox.confirm(`确认弃审请购单？`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true
      })
      .then(async () => {
        const obj = { ...detailCtx.editData }
        obj['blueprintName'] = JSON.stringify(obj['blueprintName']);
        obj['status'] = '0'
        const res = await requestApi.save(obj)
        if (res.code === 200) {
          ElMessage.success('弃审成功');
          detailCtx.editVisible = false
          ctx.loadData()
        }
      })
      .catch()
    }

    const data = reactive({
      ctx,
      detailCtx,
      projectOptions: [],
      requirementOptions: [],
      requirementList: [],
      requirementDialog: false,
      fileList: [],
      importLoading: false,
      requirementGoodList: [],
      requirementOrder: [],
      delGoodsList: [],
      goodsOptions: [],
      goodsOptionsCode:[],
      loading: false,
      finishLoading: false,
      getCodeObj:{},
      // blueprintName: '',
      uploadFile,
      confirm,
      tableRowStyle,
      getInventoryNum,
      getGoodsList,
      getGoodsListCode,
      handleSkuChange,
      handleSkuChangeCode,
      getRequirement,
      addRemark,
      abandon
    })

    // init
    onMounted(() => {
      getProjectList()
      ctx.loadData()
    })

    return {
      uploadRef,
      ...toRefs(data)
    }
  }
})
